package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialInventoryEntity;
import city.spring.modules.material.service.MaterialInventoryService;
import city.spring.modules.material.vo.MaterialinventoryVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：库存盘点
 *
 * @author 谢金婷
 * @date 2020-06-11 17:29:42
 */
@RestController
@RequestMapping("/inventory")
public class MaterialInventoryController extends ApiController {
    private final MaterialInventoryService inventoryService;
    private final EmployeeService employeeService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialInventoryEntity, ?>> entityOrderFields;

    public MaterialInventoryController(MaterialInventoryService inventoryService, EmployeeService employeeService) {
        this.inventoryService = inventoryService;
        this.employeeService = employeeService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialInventoryEntity::getId);
        entityOrderFields.add(MaterialInventoryEntity::getGmtCreate);
        entityOrderFields.add(MaterialInventoryEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>库存盘点</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MaterialInventoryEntity entity) {
        LambdaQueryChainWrapper<MaterialInventoryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>库存盘点</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialinventoryVO entity, Date[] recordDate) {
//        LambdaQueryChainWrapper<MaterialInventoryEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialInventoryEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MaterialInventoryEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getFounder());
//                record.setNickname(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setFounder(null);
//                record.setNickname("< 找不到盘点人员 >");
//            }
//        }
//        return success(page);
        QueryWrapper<? extends MaterialInventoryEntity> queryWrapper = buildQuery(entity);
        if (recordDate != null && recordDate.length == 2) {
            queryWrapper.ge("t1.record_date", recordDate[0]);
            queryWrapper.le("t1.record_date", recordDate[1]);
        }
        return success(inventoryService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>库存盘点</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(inventoryService.getMaterialinventoryById(id));
        QueryWrapper<MaterialinventoryVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialinventoryVO> records = inventoryService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>库存盘点</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialInventoryEntity entity, @NonNull Principal user) {
        inventoryService.saveInventory(entity, user);

        return success(entity);
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>库存盘点</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialInventoryEntity entity) {
        entity.setId(id);
        inventoryService.updateInventory(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>库存盘点</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        inventoryService.deleteInventory(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>库存盘点</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        inventoryService.deleteInventory(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialInventoryEntity> buildLambdaQuery(MaterialInventoryEntity entity) {
        LambdaQueryChainWrapper<MaterialInventoryEntity> lambdaQuery = inventoryService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MaterialInventoryEntity::getId, entity.getId());
//        lambdaQuery.like(entity.getMaterialId() != null, MaterialInventoryEntity::getMaterialId, entity.getMaterialId());
//        lambdaQuery.eq(entity.getInventoryquantity() != null, MaterialInventoryEntity::getInventoryquantity, entity.getInventoryquantity());
//        lambdaQuery.eq(entity.getProfitAndLoss() != null, MaterialInventoryEntity::getProfitAndLoss, entity.getProfitAndLoss());
//        lambdaQuery.like(entity.getUserId() != null, MaterialInventoryEntity::getUserId, entity.getUserId());
        lambdaQuery.eq(entity.getGmtCreate() != null, MaterialInventoryEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MaterialInventoryEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    private QueryWrapper<MaterialInventoryEntity> buildQuery(MaterialinventoryVO entity) {
        QueryWrapper<MaterialInventoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t2.sname", entity.getSname());
        wrapper.like(StringUtils.isNotBlank(entity.getFounder()), "t1.founder", entity.getFounder());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t3.name", entity.getName());
        return wrapper;
    }

    /**
     * 查询所有盘点记录,根据创建时间排序
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getInventoryOrder")
    public Object getInventoryOrder(Pageable pageable) {
        return success(inventoryService.getInventoryOrder(pageable));
    }

}
